<template>
  <div class="common-sense-accumulation">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>常识积累管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">新增常识积累</el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
          </div>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="请输入标题或内容关键词" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden;"
              v-model="form.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="常识积累详情" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="标题">{{ detailData.title }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ detailData.category }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(detailData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(detailData.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="内容">
          <div class="content-detail" v-html="detailData.content"></div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getCommonSenseAccumulations, 
  addCommonSenseAccumulation, 
  updateCommonSenseAccumulation, 
  deleteCommonSenseAccumulation,
  batchDeleteCommonSenseAccumulations
} from '@/api/commonSenseAccumulation'

// 富文本编辑器相关导入
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { createEditorRef, getEditorConfig, getToolbarConfig, createEditorCallback } from '@/utils/editorUtils'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 富文本编辑器相关
const editorRef = createEditorRef()
const mode = 'default'
const editorConfig = getEditorConfig('请输入内容...', '常识积累')
const toolbarConfig = getToolbarConfig()
const handleCreated = createEditorCallback(editorRef)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const detailDialogVisible = ref(false)

// 表单数据
const form = reactive({
  id: null,
  title: '',
  content: '',
  category: ''
})

// 详情数据
const detailData = reactive({
  id: null,
  title: '',
  content: '',
  category: '',
  createTime: '',
  updateTime: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

// 表单引用
const formRef = ref()

// 格式化时间
const formatTime = (time: string | number | Date) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条常识积累吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map((item: any) => item.id)
      const res = await batchDeleteCommonSenseAccumulations(ids)
      if (res && res.code === 200) {
        ElMessage.success('批量删除成功')
        fetchData()
        // 清空选择
        selectedRows.value = []
      } else {
        ElMessage.error(res?.message || '批量删除失败')
      }
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  })
}

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getCommonSenseAccumulations()
    console.log('常识积累响应数据:', res)
    
    // 添加详细的条件检查日志
    console.log('条件检查:', {
      resExists: !!res,
      resCode: res && res.code,
      isCode200: res && res.code === 200
    })
    
    if (res && res.code === 200) {
      // 检查数据是否存在
      if (res.data) {
        tableData.value = res.data
        pagination.total = res.data.length
      } else {
        // 如果data为null或undefined，设置为空数组
        tableData.value = []
        pagination.total = 0
      }
      // 成功获取数据，清除错误消息
      console.log('常识积累数据获取成功')
    } else {
      console.error('常识积累获取数据失败:', res?.message)
      ElMessage.error(res?.message || '获取数据失败')
    }
  } catch (error) {
    console.error('常识积累获取数据异常:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 实际项目中应该调用搜索接口
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增常识积累'
  isEdit.value = false
  // 重置表单
  Object.assign(form, {
    id: null,
    title: '',
    content: '',
    category: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑常识积累'
  isEdit.value = true
  // 填充表单数据
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看详情
const handleView = (row: any) => {
  Object.assign(detailData, row)
  detailDialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这条常识积累吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteCommonSenseAccumulation(row.id)
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res
        if (isEdit.value) {
          // 编辑
          res = await updateCommonSenseAccumulation(form)
        } else {
          // 新增
          res = await addCommonSenseAccumulation(form)
        }
        
        console.log('提交响应数据:', res)
        
        // 检查响应数据结构
        if (res && res.code === 200) {
          ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          fetchData()
        } else {
          console.error('提交失败:', res?.message || '未知错误')
          ElMessage.error(res?.message || (isEdit.value ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error('提交异常:', error)
        ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
      }
    }
  })
}

// 对话框关闭事件
const handleDialogClose = () => {
  formRef.value.resetFields()
}

// 分页事件
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.common-sense-accumulation {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.content-detail {
  white-space: pre-wrap;
  line-height: 1.6;
}
</style>